﻿using Ccteg.Common;
using Microsoft.Extensions.Logging;
using Quartz;
using Quartz.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Xml;

namespace Ccteg.JobHostQuartz
{
    public class JobSchedulerWork
    {
        private static Dictionary<long, TaskWork> _tasks = new Dictionary<long, TaskWork>();
        private static Thread th;
        private static IServiceProvider _serviceProvider;
        public static void OnStart(IServiceProvider IServiceProvider)
        {
            _serviceProvider = IServiceProvider;
            ThreadStart srvStart = new ThreadStart(ServiceImp);
            th = new Thread(srvStart);
            th.IsBackground = true;
            th.Start();
        }
        public static void OnStop()
        {
            try
            {
                var sch = OnSchedule().FindAll(x => x.ISDELETE == 0); // DB.Query<Schedule>().Select(x => x.All()).Where(x => x.ISDELETE == 0).ToList();
                foreach (var item in _tasks)
                {
                    var csch = sch.Find(x => x.ID == item.Key);
                    if (csch != null && _tasks.ContainsKey(csch.ID))
                    {
                        item.Value.StopTaskById(sch.Find(x => x.ID == item.Key));
                    }

                }

                _tasks.Clear();
                th.Abort();


                //EmailManager.sendEmail(title + "任务调度服务停止", string.Format("任务调度后台服务停止，停止时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            }
            catch (Exception ex)
            {
                //EmailManager.sendEmail(title + "任务调度服务停止异常", string.Format("异常原因:{0},{1},{2}", ex.Message, ex.StackTrace, ex.InnerException));
                throw;
            }
        }
        public static void ServiceImp()
        {
            var _Logger = _serviceProvider.GetService(typeof(ILoggerFactory)) as ILoggerFactory;
            _Logger.CreateLogger<JobSchedulerWork>().LogInformation($"任务调度后台服务启动，启动时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}");
            //EmailManager.sendEmail(title + "任务调度服务启动", string.Format("任务调度后台服务启动，启动时间:{0}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")));
            try
            {
                while (true)
                {
                    var cursch = OnSchedule();
                    //var cursch = DB.Query<Schedule>().Select(x=>x.All()).Where(x=>x.ISDELETE ==0).ToList();
                    foreach (var item in cursch)
                    {

                        if (item.ISDELETE == 1 || item.JOBSTATE == 0)
                        {
                            if (_tasks.ContainsKey(item.ID))
                            {
                                _tasks[item.ID].StopTaskById(item);
                                _tasks.Remove(item.ID);
                            }
                        }
                        else if (item.JOBSTATE == 1 && item.ISDELETE == 0)
                        {
                            if (!_tasks.ContainsKey(item.ID))
                            {
                                _tasks.Add(item.ID, new TaskWork());
                                _tasks[item.ID].RunNewTaskById(item, _serviceProvider);
                            }

                        }
                        else if (item.JOBSTATE == 0 && item.ISDELETE == 0)
                        {
                            if (_tasks.ContainsKey(item.ID))
                            {
                                _tasks[item.ID].StopTaskById(item);
                                _tasks.Remove(item.ID);
                            }
                        }

                    }

                    Thread.Sleep(new TimeSpan(0, 50, 0));
                    //Thread.Sleep(1000);
                }
            }
            catch (Exception exception)
            {
                _Logger.CreateLogger<JobSchedulerWork>().LogError($"任务调度后台服务启动，任务调度后台服务异常，启动时间:{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")}异常原因:{exception.Message}");
                //EmailManager.sendEmail(title + "任务调度服务启动", string.Format("任务调度后台服务异常，异常原因:{0}\r\n{1}\r\n{2}", exception.Message, exception.InnerException, exception.StackTrace));
            }
        }
        public static List<Schedule> OnSchedule()
        {
            List<Schedule> scheduleList = new List<Schedule>();
            try
            {
                XmlDocument xml = new XmlDocument();
                string path = AppContext.BaseDirectory + "Config/ScheduleConfig.xml";
                xml.Load(path);
                var applyNodes = xml.SelectNodes("/Applies/Model");
                for (var i = 0; i < applyNodes.Count; i++)
                {
                    XmlNode node = applyNodes[i];
                    Schedule model = new Schedule();
                    model = (Schedule)XmlHelper.XMLToModel(node.OuterXml, model);
                    scheduleList.Add(model);
                }
            }
            catch (Exception ex)
            {
            }
            return scheduleList;
        }
    }
}
